var map;
var polys = [];	
var labels = [];
var markers = [];
var airportMarkers = [];
var isListener = 0;

document.onkeydown = keypressHandler;
document.location.hasFocus = false;

/**
This is the key handler function, for when a user presses the up arrow,
down arrow, tab key, or enter key from the input field.
*/
function keypressHandler (evt) {
    // make sure we have a valid event variable
    if(!evt && window.event) {
  	evt = window.event;
    }
    var key = evt.keyCode;

    if ( key == 13 && document.location.hasFocus ) {
    	gotoLocation();
    	document.location.hasFocus = false;
    }
    
    return true;
}

function setFocus(f) {
	f.hasFocus = true;
}

function unsetFocus(f) {
	f.hasFocus = false;
}

function savePanel() {
	document.getElementById("loading").innerHTML = ' Enter Email: <input id="email" type="text" size="20" /><input type="button" value="Send" onclick="saveMap()" /><div id="warning"></div>';
}

function saveMap () {
	var save = [];
	var isAssigned = 0;
	for (var i=0; i<polys.length; i++) {
			 if (polys[i].color == "#ff0000") save[i] = 'r';
		else if (polys[i].color == "#0000ff") save[i] = 'd';
		else if (polys[i].color == "#ff8888") save[i] = 'r';
		else if (polys[i].color == "#8888ff") save[i] = 'd';			
		else { save[i] = 'u'; isAssigned = 1;}
	}
	var checkEmail = document.getElementById('email').value;
	if(isAssigned == 1) {
		document.getElementById("warning").style.background = "#f00";
		document.getElementById("warning").innerHTML = "Error: Please assign all states and then Submit";
		grayStates();
	}
	else if ((checkEmail.indexOf('@') < 0) || ((checkEmail.charAt(checkEmail.length-4) != '.') && (checkEmail.charAt(checkEmail.length-3) != '.'))) {
		document.getElementById("warning").style.background = "#f00";
		document.getElementById("warning").innerHTML = "Error: Please enter valid email address";
	}
	else if (isAssigned == 0) {
		var output = '?email=' + document.getElementById('email').value + '&votes=';
		for(var i=0;i<51;i++) output += save[i];
		document.getElementById("loading").innerHTML = 'Thank You!<iframe id="php2" name="php2" style="overflow:hidden; width:0px; height:0px; border: 1px;background:#fff" src="http://mapmash.100webspace.net/vote.php' + output + '"></iframe><iframe id="php" name="php" style="overflow:hidden; width:0px; height:0px; border: 1px;background:#fff" src="http://rakf1.110mb.com/vote.php' + output + '"></iframe>';
	}
}


function addPoly (i) {
	map.addOverlay(polys[i]);
	GEvent.addListener(polys[i], "click", function() {
		if(polys[i].color == "#999999") {polys[i].color = "#ff0000";polys[i].setFillStyle({color:"#ff0000"});}
		else if(polys[i].color == "#ff0000") {polys[i].color = "#0000ff";polys[i].setFillStyle({color:"#0000ff"});}
		else if(polys[i].color == "#0000ff") {polys[i].color = "#999999";polys[i].setFillStyle({color:"#999999"});}	
		else {polys[i].color = "#999999";polys[i].setFillStyle({color:"#999999"});}
		map.addOverlay(polys[i]);
		calculate();
	});
//	GEvent.addListener(polys[i], "mouseover", function() {
//		polys[i].setStrokeStyle({color:"#ffffff",weight:"5"});
//		map.addOverlay(polys[i]);
//	});
//	GEvent.addListener(polys[i], "mouseout", function() {
//		polys[i].setStrokeStyle({color:"#000000",weight:"0.5"});
//		map.addOverlay(polys[i]);
//	});	
}

function initHighpointData (feedObj) {

	var state_data = feedObj["feed"].entry;

	var hpHTML = "";
	var state,latitude,longitude,row, elevation;
	var i=0;
	var iconObj = MapIconMaker.createLabeledMarkerIcon({label: ' ', primaryColor: "#f9c203"});
	
	for (key in state_data) {
		state = '';
		name = '';
		latitude = '';
		longitude = '';
		elevation = '';
		
		row = state_data[key];
		state = row.gsx$state.$t;
		name = row.gsx$name.$t;
		latitude = row.gsx$latitude.$t;
		longitude = row.gsx$longitude.$t;
		elevation = row.gsx$elevation.$t;
		
		if (state != '' && name != '' && latitude != '' && longitude!= '') {
			hpHTML = "<b>" + name + "</b><br>Elevation: " + elevation + " feet";
			markers[i++] = createMarker(latitude,longitude,name,hpHTML,iconObj);
		}
	}
	document.getElementById("loading").innerHTML = "";
	showAirports();
}

/*
function createMarker (i,lat_,lng_,name_) {
	var newIcon = MapIconMaker.createLabeledMarkerIcon({label: ' ', primaryColor: "#f9c203"});
	markers[i] = new GMarker(new GLatLng(lat_,lng_), {icon:newIcon,title: name_});
	GEvent.addListener(markers[i], "click", function(overlay,point) {
		//TODO: Handle marker click here
	});		
	map.addOverlay(markers[i]);
}*/

function createMarker(lat,lng,name,html,iconObj) {
	var marker = new GMarker(new GLatLng(lat,lng), {icon:iconObj,title: name})
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	});   
	map.addOverlay(marker);
	return marker;	  
}

function toggleAiports(button) {
	
	// Swap the style
    button.className = (button.className=="down") ? "up" : "down";
}

function showAirports() { 
	var marker;
	for (key in airports) {
		airportMarkers[key] = createMarker(
			airports[key][AP_LATITUDE],
			airports[key][AP_LONGITUDE],
			"",
			airports[key][AP_INFO],
			plane);
	}
}
/*
function toggle_marker (check) {
	for (var i=0; i<polys.length; i++)
		if (check == true) map.addOverlay(markers[i]);
		else if (check == false) map.removeOverlay(markers[i]);	
}
*/

function load(){
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"),{draggableCursor: 'pointer'});
		map.addMapType(G_NORMAL_MAP);
		map.addMapType(MYTOPO_MAP);
		map.addMapType(G_PHYSICAL_MAP);
		map.setMapType(G_PHYSICAL_MAP);
		map.addControl(new GLargeMapControl3D(),new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7,43)));
		map.addControl(new GMapTypeControl(),new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7,43)));
		map.addControl(new GScaleControl);
		//map.disableDoubleClickZoom();

		//Center on US Default
		if(document.getElementById("map").offsetWidth < 600)
			map.setCenter(new GLatLng(40,-96), 3); 
		else
			map.setCenter(new GLatLng(40,-96), 4);
		var start = new GPoint(39,-96);
		
		//TODO: Switch here on regions.
		
		//map.openInfoWindowHtml(new GLatLng(33,-100), '<span class="text1"><br><center>Click on a highpoint marker to learn more about it.<br><center></span>');

		document.getElementById("loading").innerHTML = '&nbsp;Loading...&nbsp;';

			var script = document.createElement('script');  

		//Highpoint data source: https://docs.google.com/spreadsheet/ccc?key=0Aj736pFE_zyxdDdlUFIyVkJ0TFpyc0xyVkRZN3FLYkE&hl=en_US       
		script.setAttribute('src', 'https://spreadsheets.google.com/feeds/list/0Aj736pFE_zyxdDdlUFIyVkJ0TFpyc0xyVkRZN3FLYkE/od6/public/values?alt=json-in-script&callback=initHighpointData');
		script.setAttribute('id', 'jsonScript');
		script.setAttribute('type', 'text/javascript');
		document.documentElement.firstChild.appendChild(script);  
		
        /* Read in state polygons
	    var request = GXmlHttp.create();
	    request.open("GET", "states.xml", true);
		request.onreadystatechange = function() {
        if (request.readyState == 4) {
            var xmlDoc = GXml.parse(request.responseText);
            var states = xmlDoc.documentElement.getElementsByTagName("state");
            for (var a = 0; a < states.length; a++) {
                var label  = states[a].getAttribute("name");
                var colour = states[a].getAttribute("colour");
                var points = states[a].getElementsByTagName("point");
                var pts = [];
                for (var i = 0; i < points.length; i++) {
                    pts[i] = new GLatLng(parseFloat(points[i].getAttribute("lat")), parseFloat(points[i].getAttribute("lng")));
                }
                var poly = new GPolygon(pts,"#000000",0.5,0.5,colour,0.5);
                polys.push(poly);
                labels.push(label);
                createMarker(a,states[a].getAttribute("lat"),states[a].getAttribute("lng"), states[a].getAttribute("name"));
                addPoly(a);
            }
        }  
        request.send(null);
        */
	}   
}